package com.itboye.shop.me.qianbao;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.shop.R;
import com.itboye.shop.alipay.OrderInfoUtil2_0;
import com.itboye.shop.alipay.PayResult;
import com.itboye.shop.base.BaseActivity;
import com.itboye.shop.bean.GoPayBean;
import com.itboye.shop.bean.WeiXinPayBean;
import com.itboye.shop.net.ResultEntity;
import com.itboye.shop.presenter.YuEPresenter;
import com.itboye.shop.util.loadutil.IsUtilUid;
import com.itboye.shop.util.loadutil.MAlert;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 充值
 */
public class ChongZhiActivity extends BaseActivity implements Observer{
    TextView tvTitle;
    ImageView back;

    ImageView zhifubao_check,weixin_check;
    EditText chongzhi_money;
    Button chongzhi_ok;

    private int payType = 1;//默认为1支付宝
    boolean isZFB = true, isWX;

    YuEPresenter presenter;
    GoPayBean bean;
    WeiXinPayBean weixinBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chong_zhi);

        tvTitle.setText("账户充值");

        presenter=new YuEPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.chongzhi_ok:
                switch (payType) {
                    case 1:
                        isZFB = true;
                        isWX = false;
                        zhifubaoPay();
                        break;
                    case 2:
                        isZFB = false;
                        isWX = true;
                        weixinPay();
                        break;
                }
                break;
            case R.id.zhifubao_check:
                setPayTypeSelected(1);
                break;
            case R.id.weixin_check:
                setPayTypeSelected(2);
                break;

            default:
                break;
        }
    }
    /**
     * 支付宝支付
     */
    private void zhifubaoPay() {
        String s= chongzhi_money.getText().toString();
        if(s.equals("")){
            MAlert.alert("请输入金额",Gravity.CENTER);
            return;
        }
        showProgressDialog("请稍后", true);
        double m=Double.parseDouble(s)*100;
        presenter.chongZhi(IsUtilUid.isUid(),m+"");
    }
    /**
     * 微信支付
     */
    private void weixinPay() {
        String s= chongzhi_money.getText().toString();
        if(s.equals("")){
            MAlert.alert("请输入金额", Gravity.CENTER);
            return;
        }
        showProgressDialog("请稍后", true);
        presenter.chongZhi(IsUtilUid.isUid(),Double.parseDouble(s)*100+"");
    }
    /**
     * @param type 支付方式的选中状态
     *             1、支付宝
     *             3、微信
     */
    public void setPayTypeSelected(int type) {
        clearAllSelected();
        switch (type) {
            case 1:
                zhifubao_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
            case 2:
                weixin_check.setBackgroundResource(R.drawable.pay_type_selected);
        }
        payType = type;
    }
    public void clearAllSelected() {
        zhifubao_check.setBackgroundResource(R.drawable.pay_type_unselected);
        weixin_check.setBackgroundResource(R.drawable.pay_type_unselected);
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            //订单直接购买
            if (entity.getEventType() == YuEPresenter.chongzhi_success) {
                bean = (GoPayBean) entity.getData();
                MAlert.alert(bean,Gravity.CENTER);
                String pay_code=bean.getPay_code();
                if (isZFB) {
                    zfb(bean);
                }
//                if (isWX) {
//                    dingDanPresenter.WeiXinPay(bean.getPay_code());
//                }
            }
        }
        //微信预支付
//        if (entity.getEventType() == DingDanPresenter.weixin_pay_success) {
  //          weixinBean = (WeiXinPayBean) entity.getData();
//
//            PayReq req = new PayReq();
//            req.appId = weixinBean.getAppid();
//            req.partnerId = weixinBean.getPartnerid();
//            req.prepayId = weixinBean.getPrepayid();
//            req.nonceStr = weixinBean.getNoncestr();
//            req.timeStamp = weixinBean.getTimestamp();
//            req.packageValue = "Sign=WXPay";
//            req.sign = weixinBean.getSign();
//            boolean is = MyApplcation.ctx.api.sendReq(req);
//            if (is) {
////                ByAlert.alert("已调其成功");
//            } else {
//                ByAlert.alert("调起微信支付失败");
//            }
//        }
//        if (entity.getEventType() == DingDanPresenter.weixin_pay_fail) {
//            bean = (GoPayBean) entity.getData();
//        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "2016122704665497";

    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "2088221666614017";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    public static final String RSA_PRIVATE="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsNiOkk2F22n5WgY/6qUhMFSLU03IB4OSpOzB3/kTXRQUvQVRCmikKLTlRQgHPbQfdUrRycIWK3+GDeXfqK7mr9Nb8KZzpjNteCdD1z+TA/xbcHumPd4v3Z7pcYdoFGdVmvyxUDcnn1DUHlDHeEKez3CSGl1zHUIyKYW0ypEX5BNL4KWC/rch/Ycr9mQhp+83vml7ccLBL22LD6MUyp8h0x2JYEouaJQ4ptNagZdt3FOiGIptTJm5FjHUw9Dyh8BdToxY0nPcRLckQiW6NE7a7fx9Phxpa9/USVmsxIU3muD0qIgVUATVxIfQfhDkH31Q+ovNezARgvDdA5qEph7dtAgMBAAECggEALk18NeLeoMtMjsvVP4tGghZowBp+G90w/gOJG6pFLjBDnZoOIr46bJ8OOzfpLrFdHPgAxohUj6t0ghol0NOi34Y8S56QrwcNcHJpOb6E/hNYPSUenVGCU6oTJIW2zgpNI4whShRPBkM7YudIpTGLNcPqGjoWWwzgTNC3QJeErNhan/FcqxwiMX0+ag9lELU7Fzz4XnW3keUu+eAszjbOlSjdGiCjKiDVlctQQ1blgKAh2+ArRSeRmXkxgUXrFO69zO7fr4YvHPJiB6PPPgNHQRL8LsTPjWxY+5EbvnlGXou791Gdf+chRTq3p6P5zZuNr6xgAWzuHdQolIa2jkDqbQKBgQDqLKG+yg7q/e9Oy28u7McJ8uGXY1AFo7zQnv8tFCZV8iSHtmto1p5t4DV3XfY8cdfYQji0NwdBHtRctu93LRmVgLtcpbPGrjVDElfBvPisKZ8QdEHG/WtXDwuZwKKimy/1sL0OEskCrndRIkJbgs65QPG4vUEBLcgJIpmle88rdwKBgQC8QxT3xSwS/ThuowVLhNCGQ9JPkPtFVCaFBkGF5S7uN7y5jRIAGmO4Hl1yt7vWhlrw2voG4M5JkVCgbIt//C84Pl/ZT5ln5YrWITWKjuVXayAQsM4h3V5/xD0oPIq+iGsOQv4fuPruQU7v1nyyn9ILB08cW3mObO56q+5cO6OlOwKBgQDdwfJR6KsD4gFzTrc1ash6JWV4pXWsQYiWz1q656/+B9aMJjXFDCjvyDkZlwON7gkHJH7qOopGItncCujupOjraQMFE24RofuSTpaIQ1oCP1AAlveLZ4T05qyHp6Lb9bYPJpWB9Ewim/EmBhls64y0ZkoCNkaOxTn/XKK/0WU4tQKBgBf13bRPJvXfvo/uNZ1P8Q41kY3I4QII3MIvcqVs7tUoyN9Awhq7QRfM3Y3dLo32GZrv88RuVjLsyLsyNWr7mLLq1V4eEGM1xr7MCTlySGQg4Trelc2flAhk3HfDhNENIbr18cvtyhoKu9YwkTxWtO/sZTgxuD3VRWDdgv/AI2rDAoGAFSj4/5YC1SwOZnVqMdA69wJUxEyBBWpwBU2Gln3IgggtVIkbLYk7P5PwWgTmShz0NmQgCKon0Eu8M1AI3fbZJUAAZdtnqHgJ+9synjqnsOTXdRKmCcaS9s/W3pVrQ6yEsCN2vK+7gMQN2MhKJTO5IYQmUyVWRh2+a5n3i41fwps=";

    private static final int SDK_PAY_FLAG = 1;
    /**
     * 支付宝
     */
    private void zfb(GoPayBean bean){
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        String money=bean.getPay_money();
        double m=Double.parseDouble(money)/100;
        String content=bean.getPay_code();
        String code=bean.getPay_code();
        String time=bean.getCreate_time();
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID,m+"",content,code,time);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ChongZhiActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ChongZhiActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ChongZhiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };
}
